package com.henu.engineer.controller.student

import com.alibaba.fastjson.JSONObject
import com.henu.engineer.StringUtils
import com.henu.engineer.service.LoginService
import com.henu.engineer.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

/**
 *
 * @author noexcept
 * @since 2021/8/23 17:46
 */
@RestController
@RequestMapping("/st")
class StudentInfoController {

    @Autowired
    lateinit var loginService: LoginService

    @Autowired
    lateinit var userService: UserService

    /**
     * 获取学生信息
     */
    @GetMapping("/info")
    @CrossOrigin
    fun getStudentInfo(): String {
        val res = JSONObject()

        if (loginService.currentStudent == null) {
            res["code"] = 0
            res["msg"] = "当前非学生用户登录"
            return res.toJSONString()
        } else {
            val student = userService.getStudentInfo(loginService.currentUserId!!)
            if (student == null) {
                res["code"] = 0
                res["msg"] = "查询失败"
            } else {
                res["code"] = 1
                res["msg"] = "success"
            }
            res["res"] = student
            return res.toJSONString()
        }
    }

    @PostMapping("/info")
    fun updateContactAndIdentity(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 0
            res["msg"] = "parameters are incomplete"
            return res.toJSONString()
        }

        val contact = jsonObject["contact"] as String?
        val identity = jsonObject["identity"] as String?

        return when {
            StringUtils.isEmpty(contact, identity) -> {
                res["code"] = 0
                res["msg"] = "parameters are incomplete"
                res.toJSONString()
            }
            loginService.currentStudent == null -> {
                res["code"] = 0
                res["msg"] = "当前非学生用户登录"
                res.toJSONString()
            }
            else -> {
                userService.updateStudentInfo(loginService.currentUserId!!, "identity", identity!!)
                userService.updateStudentInfo(loginService.currentUserId!!, "contact", contact!!)
                res["code"] = 1
                res["msg"] = "success"
                res.toJSONString()
            }
        }
    }
}